package snippet;

import java.io.IOException;
import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;

public class ExPeer
    implements
        DiscoveryListener
{
    private Vector<RemoteDevice> devices;
    private Vector<Object> services;
    private final String uuidgenstring = "b7b63232c6b111e08d04485b39f7f2e4";
    private Object lock;
    private StreamConnection sc;
    private DiscoveryAgent dAgent;
    private LocalDevice localDevice;

    public ExPeer()
    {
        devices = new Vector<RemoteDevice>();
        services = new Vector<Object>();
        lock = new Object();

        try {
            localDevice = LocalDevice.getLocalDevice();
            dAgent = localDevice.getDiscoveryAgent();
        } catch( BluetoothStateException e ) {
            System.out.println( "Não foi possivel adquirir localDevice" );
        }
    }

    @Override
    public void deviceDiscovered(
        RemoteDevice remoteDevice,
        DeviceClass deviceClass )
    {
        if( ! devices.contains( remoteDevice ) )
            devices.add( remoteDevice );
    }

    @Override
    public void inquiryCompleted(
        int arg0 )
    {
        listarDipositivos( devices );
        synchronized( lock ) {
            lock.notify();
        }
    }

    @Override
    public void serviceSearchCompleted(
        int arg0,
        int arg1 )
    {
        try {
            System.out.println( "Conectando com o primeiro da lista" );
            if( services.size() > 0  ) {
                sc = (StreamConnection) Connector.open(( (ServiceRecord) services.elementAt( 0 ) ).getConnectionURL( 0, false ));
            }else {
                System.out.println("Serviços não identificados");
            }
            
        } catch( IOException e ) {
            System.out.println( "Problema no URL de serviço!" );
            e.printStackTrace();
        }
        synchronized( lock ) {
            lock.notify();
        }
    }

    @Override
    public void servicesDiscovered(
        int arg0,
        ServiceRecord[] serviceRecords )
    {
        for( int i = 0; ( ( serviceRecords != null ) && ( i < serviceRecords.length ) ); i++ ) {
            services.addElement( serviceRecords[ i ] );
        }

        synchronized( lock ) {
            lock.notify();
        }
    }

    private void listarDipositivos(
        Vector<RemoteDevice> vet )
    {
        int size = vet.size();

        if( size <= 0 ) {
            System.out.println( "Sem disposistivos" );
        } else {
            RemoteDevice rd;
            for( int i = 0; i < size; i++ ) {
                rd = vet.elementAt( i );
                System.out.println( ( i + 1 ) + ">" + rd.getBluetoothAddress() );
            }
        }
    }

    private void comecarInquiry()
    {
        try {
            System.out.println( "Começa inquiry..." );
            dAgent.startInquiry( DiscoveryAgent.GIAC, this );
        } catch( BluetoothStateException e ) {
            System.out.println( "Não foi possivel fazer inquiry!" );
            e.printStackTrace();
        }
        try {
            synchronized( lock ) {
                lock.wait();
            }
        } catch( InterruptedException e ) {
            e.printStackTrace();
        }
    }

    private void buscarServicos(
        int indice )
    {
        assert ( ( indice >= 0 ) && ( indice < devices.size() ) );
        RemoteDevice rd = devices.elementAt( indice );
        UUID[] uuidset = new UUID[ 1 ];
        uuidset[ 0 ] = new UUID( uuidgenstring, false );
        try {
            System.out.println( "Começa busca pelo serviço..." );
            dAgent.searchServices( null, uuidset, rd, this );
        } catch( BluetoothStateException e ) {
            System.out.println( "Sem capacidade de buscar serviços!" );
            e.printStackTrace();
        }
        try {
            synchronized( lock ) {
                lock.wait();
            }
        } catch( InterruptedException e ) {
            e.printStackTrace();
        }
    }

    public static void main(
        String[] args )
    {
        ExPeer exPeer = new ExPeer();
        exPeer.comecarInquiry();
        exPeer.buscarServicos( 0 );
    }
}